﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;
using System.Configuration;
using System.Xml;

namespace ccvmscollect
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        #region 属性	
        
        /// <summary>
        /// 关键字标签 (默认娱乐)
        /// </summary>
        int tagid = 12;
        /// <summary>
        /// 视频开始ID
        /// </summary>
        int videobeginid = 0;

        private CollectLib.Manage _manage;
        public CollectLib.Manage Manage
        {
            get { return _manage ?? (_manage = new CollectLib.Manage()); }
        }

	    #endregion

        protected void Button1_Click(object sender, EventArgs e)
        {
            //if (cmblaiyuan.Text == "youku")
            //if (cmblaiyuan.Text == "youku")
            //    youkuadd();
            //else if (cmblaiyuan.Text == "tudou")
            //    tudouAdd();
            //else if (cmblaiyuan.Text.IndexOf("qiyi") >= 0)
            //    iqiyiAdd();
            //else if (cmblaiyuan.Text == "shipin")
            //{
            //    shipinaddByID();
            //}
           
           
            if (DialogResult.Yes == MessageBox.Show("专辑地址确定是:"+txtUrl.Text,"提示",MessageBoxButtons.YesNo))
            {
                BeginAdd();
            }

            
        }
  
        private void BeginAdd()
        {
            if (txtUrl.Text.IndexOf("ID") == -1)
            {
                MessageBox.Show("地址中必须包含$ID$字符");
                return;
            }
            try
            {
                this.progressBar1.Value = 0;
                this.progressBar1.Maximum = (Convert.ToInt32(txtEndUrl.Text.Trim()) - Convert.ToInt32(txtBenUrl.Text.Trim())) + 1;
                for (var i = Convert.ToInt32(txtEndUrl.Text.Trim()); i >= Convert.ToInt32(txtBenUrl.Text.Trim()); i--)
                {
                    var url = txtUrl.Text.Trim().Replace("$ID$", i.ToString());
                    try
                    {
                        this.progressBar1.Value = this.progressBar1.Value + 1;
                        ForInsert(url);
                        if (i % 2 == 0)
                        {
                            Manage.CreatXml(ConfigurationManager.AppSettings["wangzhi"]);
                        }
                    }
                    catch (Exception ex)
                    {
                        CollectLib.Err.writeInLog(ex.Message);
                        Thread.Sleep(5000);
                    }
                }
            }
            catch (Exception ex)
            {
                CollectLib.Err.writeInLog(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        #region 循环添加
        private void ForInsert(string url)
        {
            var list = GetItemList(url);
            var time = this.getTime();          
            foreach (var listitem in list)
            {
                if (listitem.Length < 300 || listitem.Contains("没有找到任何结果")) continue;
                try
                {
                    var videotype = 4;

                    if (cmblaiyuan.Text.Contains("youku")||cmblaiyuan.Text.Contains("tudou")||cmblaiyuan.Text.IndexOf("qiyi")>=0)
                    {
                        videotype = 4;
                    }
                  
                    var itemurl = GetItemUrl(listitem);
                   
                    var bofangneirongye = GetHtmlCode(itemurl);
                    var videourl = Getvideo(itemurl);
                 
                    var videodesc = Getmiaoshu(bofangneirongye);

                    var videotitle = checkTitle.Checked ? Gettitle(listitem) : Gettitle(bofangneirongye);
                    if (videotitle.IndexOf("-") > 0)
                        videotitle = videotitle.Substring(0, videotitle.IndexOf("-"));
                    var videoimg = checkImg.Checked ? Getimg(listitem) : Getimg(bofangneirongye);
                    videodesc = videodesc == "" ? videotitle : videodesc;
                    videobeginid++;
                    int pindaoid = Convert.ToInt32(cmbpindao.SelectedValue);
                    tagid = GetTagidbyPindaoid(pindaoid); //获取频道对应的tagid 
                    foreach (DataRow dr in pindaodt.Rows)
                    {
                        if (videotitle.Contains(dr["description"].ToString()))
                        {
                            pindaoid =Convert.ToInt32(dr["pindaoid"].ToString());                           
                            tagid = GetTagidbyPindaoid(pindaoid); //获取频道对应的tagid 
                            break;
                        }
                    }
                    if (pindaoid == Convert.ToInt32(cmbpindao.SelectedValue)&&cbWudao.Checked)
                    {
                        if (videotitle.IndexOf("舞")==-1)
                        {
                            continue;
                        }
                    }

                    #region 下载图片，重命名，并自动上传至服务器，

                    var wc = new WebClient();
                    var preStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    preStr = preStr + ".jpg";//生成图片名称
                    //下载的图片存储在文件夹中
                    wc.DownloadFile(videoimg, preStr);
                    videoimg = "video/" + (DateTime.Now.Month < 10
                                   ? DateTime.Now.Year + "0" + DateTime.Now.Month + "/" + preStr
                                   : DateTime.Now.Year.ToString() + DateTime.Now.Month + "/" + preStr);
                    File.Copy(preStr, ConfigurationManager.AppSettings["imgAddress"] + (DateTime.Now.Month < 10
                                   ? DateTime.Now.Year + "0" + DateTime.Now.Month + "/" + preStr
                                   : DateTime.Now.Year.ToString() + DateTime.Now.Month + "/" + preStr));
                    File.Delete(preStr);

                    #endregion
                    
                    var sql = @"insert into ccvms_video(uid,username,cid,type,title,videourl,createtime,description,uploadpic,pictype)
                            values(?uid,?username,?cid,?type,?title,?videourl,?createtime,?description,?uploadpic,?pictype)";

                    string[] param1 ={"?uid","?username","?cid","?type","?title","?videourl",
                    "?createtime","?description","?uploadpic","?pictype" };
                    object[] value1 = { 2, "admin", pindaoid, videotype, videotitle, videourl, time, videodesc, videoimg, 2 };
                    var id = 0;
                    try
                    {
                        id = Manage.ExecSqlAndReturnID(sql, param1, value1);
                        sql = "insert into ccvms_videotag(vid,tagid) values(?vid,?tagid)";
                        string[] param2 = { "?vid", "?tagid" };
                        object[] value2 = { videobeginid, tagid };
                        Manage.ExecuteUpdate(sql, param2, value2);
                    }
                    catch (Exception ex)
                    {
                        CollectLib.Err.writeInLog(ex.Message);
                        Thread.Sleep(5000);
                    }
                    if (cbCreatHtml.Checked)
                    {
                        Manage.CreatOneHtml(id, ConfigurationManager.AppSettings["wangzhi"]);
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    if (ex.Message.IndexOf("404 ") > -1 ||
                        ex.Message.IndexOf("找不到视频真实地址") > -1
                        || ex.Message.IndexOf("URI 方案无效") > -1)
                    {
                        Thread.Sleep(5000);
                        CollectLib.Err.writeInLog(ex.Message);
                        continue;
                    }
                    Thread.Sleep(10000);
                    continue;                   
                }
            }
        }

        private int GetTagidbyPindaoid(int pindaoid)
        {
            string sql = string.Format(@"select tagid from ccvms_videotag as a,ccvms_video as b where a.vid=b.vid and b.cid={0} LIMIT 0 , 1",pindaoid);
            DataTable pindaodt = Manage.GetDTBySql(sql);
            if (pindaodt.Rows.Count != 1)
            {
                MessageBox.Show("频道对应关键字未找到");
                return 1;
            }
            return Convert.ToInt32(pindaodt.Rows[0]["tagid"]);
        }
        
        #endregion
        #region 方法

        private int GetPindao(string itemurl)
        {
            var pindaoid = 0;
            //foreach (DataRow row in pindaodt.Rows)
            //{
            //    if (itemurl.IndexOf(row["pindaoname"].ToString()) > 0)
            //    {
            //        return int.Parse(row["pindaoid"].ToString());
            //    }
            //}
            if (pindaoid == 0)
            {
                pindaoid = 13;
            }
            return pindaoid;
        }
        /// <summary>
        /// 最大ID
        /// </summary>
        private void SetvVideoBeginID()
        {
            var sql = "select max(vid) from ccvms_video";
            var dt = Manage.GetDTBySql(sql);
            if (dt.Rows.Count != 1)
                throw new ApplicationException("开始id异常");
            videobeginid = int.Parse(dt.Rows[0][0].ToString());
        }
      
        /// <summary>
        /// 将开始时间转换成INT型。tosring
        /// </summary>
        private string getTime()
        {
            var start = DateTime.Now;
            var result = 0;
            var startdate = new DateTime(1970, 1, 1, 8, 0, 0);
            var seconds = start - startdate;
            result = Convert.ToInt32(seconds.TotalSeconds);
            return result.ToString();
        }

        private string GetContent(string url)
        {
            string content = GetHtmlCode(url);
            int index = content.IndexOf(txtListBegNum.Text.Trim());
            int index1 = content.IndexOf(txtListEndNum.Text.Trim());
            if (index1 == -1 || index == -1)
            {
                return "-1";
            }
            return content.Substring(index, index1 - index);
        }

        private string[] GetItemList(string url)
        {
            var begContent = GetContent(url);
            var stringSeparators = new string[] { txtSplit.Text.Trim() };
            var list = begContent.Split(stringSeparators, StringSplitOptions.None);
            return list;
        }

        private string Gettitle(string content)
        {
            int index = content.IndexOf(txtTitleBeg.Text.Trim());
            int index1 = content.IndexOf(txtTitleEnd.Text.Trim());
            if (index1 == -1 || index == -1)
            {
                return "标题未找到";
            }
            int length = txtTitleBeg.Text.Trim().Length;
            return content.Substring(index + length, (index1 - index) - length);
        }

        private string Getimg(string content)
        {
            int index = content.IndexOf(txtImgBeg.Text.Trim());
            int index1 = content.IndexOf(txtImgEnd.Text.Trim());
            if (index1 == -1 || index == -1)
            {
                return "图片地址未找到";
            }
            int length = txtImgBeg.Text.Trim().Length;
            return content.Substring(index + length, (index1 - index) - length);
        }
        /// <summary>
        /// 获取视频ID
        /// </summary>
        /// <param name="itemurl"></param>
        /// <returns></returns>
        private string Getvideiid(string itemurl)
        {
            var content = GetHtmlCode(itemurl);
            int index = content.IndexOf(txtSwfBeg.Text.Trim());
            int index1 = content.IndexOf(txtSwfEnd.Text.Trim());
            if (index1 == -1 || index == -1)
            {
                return "视频地址未找到";
            }
            int length = txtSwfBeg.Text.Trim().Length;
            return content.Substring(index + length, (index1 - index) - length);
        }
        private string Getvideo(string itemurl)
        {
            if (cmblaiyuan.Text.Contains("youku"))
            {
                var youkuid = itemurl.Substring(itemurl.IndexOf("id_") + 3, itemurl.IndexOf(".html") - itemurl.IndexOf("id_")-3);
                return "http://player.youku.com/player.php/partnerid/XMTI=/sid/" + youkuid + "/v.swf";
            }
            else if (cmblaiyuan.Text.Contains("tudou"))
            {
                var tudouid = Getvideiid(itemurl);
                return string.Format("http://js.tudouui.com/bin/player2/olc_6.swf?iid={0}&amp;autoPlay=true",tudouid);
            }
            else if (cmblaiyuan.Text.IndexOf("iqiyi")>=0)
            {
                var iqiyiid = Getvideiid(itemurl);
                return string.Format("http://www.iqiyi.com/player/20120725165047/SharePlayer.swf?vid={0}&autoPlay=true", iqiyiid);
            }
            return "";
        }
        private string Getmiaoshu(string contents)
        {
            int inde = contents.IndexOf(txtIntroBeg.Text.Trim());
            int inde1 = contents.IndexOf(txtIntroEnd.Text.Trim());
            if (inde1 == -1 || inde == -1)
            {
                return "";
            }
            int lengt = txtIntroBeg.Text.Trim().Length;
            return contents.Substring(inde + lengt, (inde1 - inde) - lengt);
        }

        private string Getcontents(string content)
        {
            int index = content.IndexOf(txtVideoUrlBeg.Text.Trim());
            if (index < 0)
            {
                throw new Exception("内容页面未找到!");
            }
            int index1 = content.IndexOf(txtVideoUrlEnd.Text.Trim());
            int length = txtVideoUrlBeg.Text.Trim().Length;
            var url = content.Substring(index + length, (index1 - index) - length);
            return GetHtmlCode(url);
        }
        /// <summary>
        /// 获取内容页
        /// </summary>
        /// <param name="listitem"></param>
        /// <returns></returns>
        private string GetItemUrl(string listitem)
        {
            int index = listitem.IndexOf(txtVideoUrlBeg.Text.Trim());
            if (index < 0)
            {
                throw new Exception("内容页面未找到!");
            }
            int index1 = listitem.IndexOf(txtVideoUrlEnd.Text.Trim());
            int length = txtVideoUrlBeg.Text.Trim().Length;
            var url = listitem.Substring(index + length, (index1 - index) - length);
            return url;
        }
        
        #endregion
        #region 加载  
        private void Form1_Load(object sender, EventArgs e)
        {
            SetvVideoBeginID();
            timer2.Start();
            timer1.Start();
            LoadPindaoDt();

        }
        DataTable pindaodt;
        private void LoadPindaoDt()
        {
            string sql = "select cid as pindaoid,htmlpath as pindaoname,description from ccvms_channel ";
            pindaodt = Manage.GetDTBySql(sql);

            cmbpindao.DataSource = pindaodt;
            cmbpindao.ValueMember = "pindaoid";
            cmbpindao.DisplayMember = "pindaoname";
        }

        private void LoadTXT(string txtname)
        {
            if (string.IsNullOrEmpty(txtname)) return;
            var reader = new StreamReader(txtname + ".txt");
            if (reader.Read() > 0)
            {
                var guolv = reader.ReadLine();
                txtUrl.Text = reader.ReadLine();
                txtBenUrl.Text = reader.ReadLine();
                txtEndUrl.Text = reader.ReadLine();
                var a = reader.ReadLine();
                // CheckReturn.Checked = a != "0";
                txtListBegNum.Text = reader.ReadLine();
                txtListEndNum.Text = reader.ReadLine();
                txtSplit.Text = reader.ReadLine();
                var b = reader.ReadLine();
                checkImg.Checked = b != "0";
                var c = reader.ReadLine();
                checkTitle.Checked = c != "0";
                txtImgBeg.Text = reader.ReadLine();
                txtImgEnd.Text = reader.ReadLine();
                txtTitleBeg.Text = reader.ReadLine();
                txtTitleEnd.Text = reader.ReadLine();
                txtVideoUrlBeg.Text = reader.ReadLine();
                txtVideoUrlEnd.Text = reader.ReadLine();
                txtSwfBeg.Text = reader.ReadLine();
                txtSwfEnd.Text = reader.ReadLine();
                txtIntroBeg.Text = reader.ReadLine();
                txtIntroEnd.Text = reader.ReadLine();
            }
            else
            {
            }
            reader.Close();
        }
        
        #endregion
        #region 读取网页源码

        private string GetHtmlCode(string url)
        {
            string htmlCode;
            var webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            webRequest.Timeout = 30000;
            webRequest.Method = "GET";
            webRequest.UserAgent = "Mozilla/4.0";
            webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            var webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
            if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
            {
                using (var streamReceive = webResponse.GetResponseStream())
                {
                    using (var zipStream =
                        new System.IO.Compression.GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress))
                    {
                        if (cmblaiyuan.Text == "tudou")
                        {
                            using (var sr = new System.IO.StreamReader(zipStream, Encoding.GetEncoding("gbk")))
                            {
                                htmlCode = sr.ReadToEnd();
                            }
                        }
                        else
                        {
                            using (var sr = new System.IO.StreamReader(zipStream, Encoding.UTF8))
                            {
                                htmlCode = sr.ReadToEnd();
                            }
                        }
                    }
                }
            }
            else
            {
                using (var streamReceive = webResponse.GetResponseStream())
                {
                    if (cmblaiyuan.Text == "tudou")
                    {
                        using (var sr = new System.IO.StreamReader(streamReceive, Encoding.GetEncoding("gbk")))
                        {
                            htmlCode = sr.ReadToEnd();
                        }
                    }
                    else
                    {
                        using (var sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8))
                        {
                            htmlCode = sr.ReadToEnd();
                        }
                    }
                }
            }

            return htmlCode;
        }
        private string GetPage(string url, Encoding encoding)
        {
            //初始化新的request对象
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            //返回Internet资源的相应
            var webResponse = (HttpWebResponse)webRequest.GetResponse();
            //获取流
            var stream = webResponse.GetResponseStream();
            //读取编码
            var reader = new StreamReader(stream, encoding);
            //整个页面内容
            var content = reader.ReadToEnd();
            reader.Close();
            webResponse.Close();
            return content;
        }
        #endregion
        #region 资源更改事件

        private void cmblaiyuan_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadTXT(cmblaiyuan.Text);
        }

        
        #endregion

        #region 分类方法

        private void youkuadd()
        {
            var list = new string[] {
                "http://www.youku.com/v_showlist/t2c97d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c96d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c85d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c100d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c87d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c84d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c91d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c86d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c92d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c98d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c104d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c105d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c99d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c103d1p$ID$.html",
                 "http://www.youku.com/v_showlist/t2c89d1p$ID$.html",
                "http://www.youku.com/v_showlist/t2c94d1p$ID$.html"
            };
            foreach (var str in list)
            {
                txtUrl.Text = str;
                txtBenUrl.Text = "1";
                txtEndUrl.Text = "2";
                BeginAdd();
            }
        }

        private void tudouAdd()
        {
            var list = new string[] {
                "http://www.tudou.com/top/vc29p$ID$p3o1.html",
                "http://www.tudou.com/top/vc30p$ID$p3o1.html",
                "http://www.tudou.com/top/vc22p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc31p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc1p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc5p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc9p$ID$p3o1.html",
                   "http://www.tudou.com/top/vc15p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc26p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc24p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc32p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc34p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc27p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc10p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc3p$ID$p3o1.html",
                  "http://www.tudou.com/top/vc21p$ID$p3o1.html",
                    "http://www.tudou.com/top/vc25p$ID$p3o1.html",
                "http://www.tudou.com/top/vc33p$ID$p3o1.html",};
            foreach (var str in list)
            {
                txtUrl.Text = str;
                txtBenUrl.Text = "1";
                txtEndUrl.Text = "30";
                BeginAdd();
            }
        }

        private void iqiyiAdd()
        {
            LoadTXT("iqiyi");
            BeginAdd();

        }

        private void tangdouAdd()
        {
            BeginAdd();
        }

        
        #endregion
        #region timer


        Thread _threadshipinadd;
        private void timer2_Tick(object sender, EventArgs e)
        {
            
            //if (_threadshipinadd != null && _threadshipinadd.ThreadState != ThreadState.Stopped) return;
            //if (DateTime.Now.ToString("HHmm") == "1830" || DateTime.Now.ToString("HHmm") == "0701")
            //{
            //    _threadshipinadd = new Thread(shipinxmladd);
            //    _threadshipinadd.Start();
            //}

        }
        private void shipinaddByID()
        {
            this.progressBar1.Value = 0;
            this.progressBar1.Maximum = (Convert.ToInt32(txtEndUrl.Text.Trim()) - Convert.ToInt32(txtBenUrl.Text.Trim())) + 1;
            for (var i = Convert.ToInt32(txtEndUrl.Text.Trim()); i >= Convert.ToInt32(txtBenUrl.Text.Trim()); i--)
            {
                var url = txtUrl.Text.Trim().Replace("$ID$", i.ToString());
                try
                {
                    this.progressBar1.Value = this.progressBar1.Value + 1;
                    shipinInsert(url);
                }
                catch (Exception ex)
                {
                    CollectLib.Err.writeInLog(ex.Message);
                    Thread.Sleep(10000);
                }
                if (i % 500 == 499)
                {
                    Manage.CreatXml(ConfigurationManager.AppSettings["wangzhi"]);
                }
            }
        }
        /// <summary>
        /// 新增单条视频
        /// </summary>
        /// <param name="url"></param>
        private void shipinInsert(string url)
        {
           

            try
            {
                var pagehtml = GetPage(url, Encoding.UTF8);
                var time = this.getTime();
                var videotype = 9;
                var videourl = GetBetweenStr(txtSwfBeg.Text, txtSwfEnd.Text, pagehtml, true);
                videourl = videourl.Replace("height=\"500\"", "height=\"460\"");
                var pindaoid = GetPindao(GetBetweenStr("<a href=\"/type/", "</a>", pagehtml, true));
                tagid = pindaoid; //获取频道对应的tagid 需要强制指定 频道id=tagid
                var videodesc = GetBetweenStr(txtIntroBeg.Text, txtIntroEnd.Text, pagehtml, true);
                var videotitle = GetBetweenStr(txtTitleBeg.Text, txtTitleEnd.Text, pagehtml, true);
                var videoimg = GetBetweenStr(txtImgBeg.Text, txtImgEnd.Text, pagehtml, false);
                videobeginid++;

                #region 下载图片，重命名，并自动上传至服务器，

                //var wc = new WebClient();
                //var preStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                //preStr = preStr + ".jpg";//生成图片名称
                ////下载的图片存储在文件夹中
                //wc.DownloadFile(videoimg, preStr);
                //videoimg = "video/" + (DateTime.Now.Month < 10
                //               ? DateTime.Now.Year + "0" + DateTime.Now.Month + "/" + preStr
                //               : DateTime.Now.Year.ToString() + DateTime.Now.Month + "/" + preStr);
                //File.Copy(preStr, ConfigurationManager.AppSettings["imgAddress"] + (DateTime.Now.Month < 10
                //               ? DateTime.Now.Year + "0" + DateTime.Now.Month + "/" + preStr
                //               : DateTime.Now.Year.ToString() + DateTime.Now.Month + "/" + preStr));
                //File.Delete(preStr);

                #endregion

                var sql = @"insert into ccvms_video(uid,username,cid,type,title,videourl,createtime,description,networkpic,pictype)
                            values(?uid,?username,?cid,?type,?title,?videourl,?createtime,?description,?networkpic,?pictype)";

                string[] param1 ={"?uid","?username","?cid","?type","?title","?videourl",
                    "?createtime","?description","?networkpic","?pictype" };
                object[] value1 = { 1, "sjzyingyuan", pindaoid, videotype, videotitle, videourl, time, videodesc, videoimg, 4 };
                var id = 0;
                try
                {
                    id = Manage.ExecSqlAndReturnID(sql, param1, value1);
                    sql = "insert into ccvms_videotag(vid,tagid) values(?vid,?tagid)";
                    string[] param2 = { "?vid", "?tagid" };
                    object[] value2 = { videobeginid, tagid };
                    Manage.ExecuteUpdate(sql, param2, value2);
                }
                catch (Exception ex)
                {
                    CollectLib.Err.writeInLog(ex.Message);
                    Thread.Sleep(5000);
                }
                Manage.CreatOneHtml(id, ConfigurationManager.AppSettings["wangzhi"]);
                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                Thread.Sleep(5000);
                CollectLib.Err.writeInLog(ex.Message);
            }
        }

        private string GetBetweenStr(string beghtml, string endhtml, string pagehtml, bool beghtmlreplace)
        {
            int index = pagehtml.IndexOf(beghtml);
            if (index == -1)
            {
                throw new Exception("内容标记未找到");
            }
            var contents = pagehtml.Substring(index);
            int indes1 = contents.IndexOf(endhtml);
            if (indes1 == -1)
            {
                throw new Exception("内容标记未找到");
            }
            return beghtmlreplace ? contents.Substring(0, indes1).Replace(beghtml, "") : contents.Substring(0, indes1);
        }

        private void shipinxmladd()
        {
            //读取xml
            string url = ConfigurationManager.AppSettings["videoxmlurl"];
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream stream = myHttpWebResponse.GetResponseStream();

            XmlTextReader reader = new XmlTextReader(stream);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            //循环添加


            XmlNode xn = xmlDoc.SelectSingleNode("document");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xn1 in xnl)
            {
                try
                {

                    // 将节点转换为元素，便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;
                    if (xe.Name != "item") continue;
                    // 得到Book节点的所有子节点
                    XmlNodeList xnl0 = xe.ChildNodes;
                    var time = this.getTime();
                    var videotype = 4;

                    var videotime =
                        xnl0.Item(7).InnerXml.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\r", "").Replace(
                            "\n", "");
                    if (Convert.ToDateTime(videotime) < DateTime.Now.AddHours(-1)) continue;
                    var videourl =
                        xnl0.Item(3).InnerXml.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\r", "").Replace(
                            "\n", "");
                    var videodesc =
                        xnl0.Item(4).InnerXml.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\r", "").Replace(
                            "\n", "");
                    var videotitle =
                        xnl0.Item(1).InnerXml.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\r", "").Replace(
                            "\n", "");
                    var videoimg =
                        xnl0.Item(5).InnerXml.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\r", "").Replace(
                            "\n", "");
                    var tagname = xnl0.Item(xnl0.Count - 1).InnerXml.Replace("<![CDATA[", "").Replace("]]>", "");
                    var pindaoid = GetPindao(tagname);
                    tagid = pindaoid; //获取频道对应的tagid 需要强制指定 频道id=tagid


                    videobeginid++;

                    #region 下载图片，重命名，并自动上传至服务器，

                    //var wc = new WebClient();
                    //var preStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    //preStr = preStr + ".jpg"; //生成图片名称
                    ////下载的图片存储在文件夹中
                    //wc.DownloadFile(videoimg, preStr);
                    //videoimg = "video/" + (DateTime.Now.Month < 10
                    //                           ? DateTime.Now.Year + "0" + DateTime.Now.Month + "/" + preStr
                    //                           : DateTime.Now.Year.ToString() + DateTime.Now.Month + "/" + preStr);
                    //File.Copy(preStr, ConfigurationManager.AppSettings["imgAddress"] + (DateTime.Now.Month < 10
                    //                                                                        ? DateTime.Now.Year + "0" +
                    //                                                                          DateTime.Now.Month + "/" +
                    //                                                                          preStr
                    //                                                                        : DateTime.Now.Year.ToString
                    //                                                                              () +
                    //                                                                          DateTime.Now.Month + "/" +
                    //                                                                          preStr));
                    //File.Delete(preStr);

                    #endregion

                    var sql =
                        @"insert into ccvms_video(uid,username,cid,type,title,videourl,createtime,description,networkpic,pictype)
                            values(?uid,?username,?cid,?type,?title,?videourl,?createtime,?description,?networkpic,?pictype)";

                    string[] param1 = {
                                          "?uid", "?username", "?cid", "?type", "?title", "?videourl",
                                          "?createtime", "?description", "?networkpic", "?pictype"
                                      };
                    object[] value1 = {
                                          1, "sjzyingyuan", pindaoid, videotype, videotitle, videourl, time, videodesc,
                                          videoimg, 4
                                      };
                    var id = 0;
                    try
                    {
                        id = Manage.ExecSqlAndReturnID(sql, param1, value1);
                        sql = "insert into ccvms_videotag(vid,tagid) values(?vid,?tagid)";
                        string[] param2 = { "?vid", "?tagid" };
                        object[] value2 = { videobeginid, tagid };
                        Manage.ExecuteUpdate(sql, param2, value2);
                    }
                    catch (Exception ex)
                    {
                        CollectLib.Err.writeInLog(ex.Message);
                        Thread.Sleep(5000);
                    }
                    Manage.CreatOneHtml(id, ConfigurationManager.AppSettings["wangzhi"]);
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    if (ex.Message.IndexOf("404 ") > -1 || ex.Message.IndexOf("URI 方案无效") > -1)
                    {
                        Thread.Sleep(5000);
                        CollectLib.Err.writeInLog(ex.Message);
                    }
                    Thread.Sleep(5000);
                }
            }
            Manage.CreatXml(ConfigurationManager.AppSettings["wangzhi"]);
        }
        private static void StartDownload()
        {
            string URL = ConfigurationManager.AppSettings["videoxml"];
            int n = URL.LastIndexOf("/");
            string URLAddress = URL.Substring(0, n);
            string fileName = URL.Substring(n + 1, URL.Length - n - 1);
            string Dir = Environment.CurrentDirectory;
            string Path = Dir.ToString() + "\\" + fileName;

            try
            {
                var client = new WebClient();
                client.DownloadFile(URLAddress, fileName);
                Stream str = client.OpenRead(URLAddress);
                StreamReader reader = new StreamReader(str);
                //statusStrip1.Text = "正在接收数据...";
                FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);
                var writer = new StreamWriter(fstr);
                while (reader.Peek() >= 0)
                {
                    char[] c = new char[10240];
                    reader.Read(c, 0, c.Length);
                    writer.Write(c);
                }
                writer.Flush();
                str.Close();
                fstr.Close();
                //statusStrip1.Text = "下载完毕！";
            }
            catch (WebException exp)
            {
                MessageBox.Show(exp.Message, "Error");
            }
        }
        #endregion
        Thread taskthread;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (taskthread == null || taskthread.ThreadState == ThreadState.Stopped)
            {               
                        
                taskthread = new Thread(Runtask);
                taskthread.Start();
            }
               
        }
        private void Runtask()
        {
            try
            {

                DataTable dt = Manage.GetDTBySql("select id, url,begpageid,endpageid,pindao from taskorder where id=(select min(id) from taskorder where tasks=0)");
                if (dt.Rows.Count == 1 && cmblaiyuan.Text.IndexOf("youku") >= 0)
                {
                    txtUrl.Text = dt.Rows[0]["url"].ToString(); ;
                    txtBenUrl.Text = dt.Rows[0]["begpageid"].ToString();
                    txtEndUrl.Text = dt.Rows[0]["endpageid"].ToString();
                    cmbpindao.Text = dt.Rows[0]["pindao"].ToString();
                    BeginAdd();
                    int id=Manage.ExecuteSql(string.Format("update taskorder set tasks=1 where id={0}", dt.Rows[0]["id"].ToString()));
                    Manage.CreatXml(ConfigurationManager.AppSettings["wangzhi"]);
                    if (id <= 0)
                    {
                        MessageBox.Show("未更新task状态");
                    }
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }   
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            int id = Manage.ExecuteSql(string.Format("update taskorder set tasks=1 where id={0}", 1));
            MessageBox.Show(id.ToString());
            return;
            taskthread = new Thread(Runtask);
            taskthread.Start();
        }



       

    }
}
